﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using Harkon.AppServer.cOne.Service;
using System.Reflection;
using System.IO;
using Harkon.AppServer.cOne.Registry;

namespace Harkon.AppServer.cOne
{
    partial class COneService : ServiceBase
    {
        public static string DeploymentPath { get; set; }
        public static IApplicationContext RootContext { get; private set; }

        public COneService()
        {
            DeploymentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            InitializeComponent();

            this.ServiceName = "COne";
            this.EventLog.Log = "Application";
            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;

            RootContext = new XmlApplicationContext("spring.config");
        }

        public void ManualStart()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            IRegistry registry = RootContext["Registry"] as IRegistry;
            ComponentInformation infrastructureComponent = RootContext["Infrastructure"] as ComponentInformation;
            registry.RegisterComponent(infrastructureComponent);

            foreach (string serviceName in RootContext.GetObjectNamesForType(typeof(ICoreService)))
            {
                ICoreService coreService = RootContext[serviceName] as ICoreService;
                ServiceName relatedServiceName = RootContext[serviceName + "Name"] as ServiceName;
                registry.RegisterService(relatedServiceName, coreService);
                coreService.Init();
                coreService.Start();
            }
        }

        public void ManualStop()
        {
            OnStop();
        }

        protected override void OnStop()
        {
            foreach (string serviceName in RootContext.GetObjectNamesForType(typeof(ICoreService)))
            {
                ICoreService coreService = RootContext[serviceName] as ICoreService;
                coreService.Stop();
            }
        }
    }
}
